home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / tar.gnu / tar-dist / buffer.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-01-26  |  28.2 KB  |  1,293 lines

  1. /* Buffer management for tar.
  2.    Copyright (C) 1988 Free Software Foundation
  3.  
  4. This file is part of GNU Tar.
  5.  
  6. GNU Tar is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 1, or (at your option)
  9. any later version.
  10.  
  11. GNU Tar is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Tar; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /*
  21.  * Buffer management for tar.
  22.  *
  23.  * Written by John Gilmore, ihnp4!hoptoad!gnu, on 25 August 1985.
  24.  *
  25.  * @(#) buffer.c 1.28 11/6/87 - gnu
  26.  */
  27.  
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include <sys/types.h>        /* For non-Berkeley systems */
  31. #include <sys/stat.h>
  32. #include <signal.h>
  33.  
  34. #ifndef MSDOS
  35. #include <sys/ioctl.h>
  36. #ifndef USG
  37. #include <sys/mtio.h>
  38. #endif
  39. #endif
  40.  
  41. #ifdef    MSDOS
  42. # include <fcntl.h>
  43. #include <process.h>
  44. #else
  45. # ifdef XENIX
  46. #  include <sys/inode.h>
  47. # endif
  48. # include <sys/file.h>
  49. #endif
  50.  
  51. extern int errno;
  52.  
  53. #include "tar.h"
  54. #include "port.h"
  55. #include "rmt.h"
  56.  
  57. /* Either stdout or stderr:  The thing we write messages (standard msgs, not
  58.    errors) to.  Stdout unless we're writing a pipe, in which case stderr */
  59. FILE *msg_file = stdout;
  60.  
  61. #define    STDIN    0        /* Standard input  file descriptor */
  62. #define    STDOUT    1        /* Standard output file descriptor */
  63.  
  64. #define    PREAD    0        /* Read  file descriptor from pipe() */
  65. #define    PWRITE    1        /* Write file descriptor from pipe() */
  66.  
  67. #ifdef __GNU__
  68. extern void    *malloc();
  69. extern void    *valloc();
  70. #else
  71. extern char    *malloc();
  72. extern char    *valloc();
  73. #endif
  74.  
  75. extern char    *index(), *strcat();
  76. extern char    *strcpy();
  77.  
  78. /*
  79.  * V7 doesn't have a #define for this.
  80.  */
  81. #ifndef O_RDONLY
  82. #define    O_RDONLY    0
  83. #endif
  84. #ifndef O_RDWR
  85. #define O_RDWR        2
  86. #endif
  87. #ifndef O_CREAT
  88. #define O_CREAT        0
  89. #endif
  90. #ifndef O_BINARY
  91. #define O_BINARY    0
  92. #endif
  93.  
  94. #define    MAGIC_STAT    105    /* Magic status returned by child, if
  95.                    it can't exec.  We hope compress/sh
  96.                    never return this status! */
  97.  
  98. void writeerror();
  99. void readerror();
  100.  
  101. void ck_pipe();
  102. void ck_close();
  103.  
  104. extern void finish_header();
  105.  
  106. /*
  107.  * The record pointed to by save_rec should not be overlaid
  108.  * when reading in a new tape block.  Copy it to record_save_area first, and
  109.  * change the pointer in *save_rec to point to record_save_area.
  110.  * Saved_recno records the record number at the time of the save.
  111.  * This is used by annofile() to print the record number of a file's
  112.  * header record.
  113.  */
  114. static union record **save_rec;
  115.  union record record_save_area;
  116. static long        saved_recno;
  117.  
  118. /*
  119.  * PID of child program, if f_compress or remote archive access.
  120.  */
  121. static int    childpid = 0;
  122.  
  123. /*
  124.  * Record number of the start of this block of records
  125.  */
  126. long    baserec;
  127.  
  128. /*
  129.  * Error recovery stuff
  130.  */
  131. static int    r_error_count;
  132.  
  133. /*
  134.  * Have we hit EOF yet?
  135.  */
  136. static int    eof;
  137.  
  138. /* JF we're reading, but we just read the last record and its time to update */
  139. extern time_to_start_writing;
  140. int file_to_switch_to= -1;    /* If remote update, close archive, and use
  141.                    this descriptor to write to */
  142.  
  143. static int volno = 1;        /* JF which volume of a multi-volume tape
  144.                    we're on */
  145.  
  146. char *save_name = 0;        /* Name of the file we are currently writing */
  147. long save_totsize;        /* total size of file we are writing.  Only
  148.                    valid if save_name is non_zero */
  149. long save_sizeleft;        /* Where we are in the file we are writing.
  150.                    Only valid if save_name is non-zero */
  151.  
  152. int write_archive_to_stdout;
  153.  
  154. /* Used by fl_read and fl_write to store the real info about saved names */
  155. static char real_s_name[NAMSIZ];
  156. static long real_s_totsize;
  157. static long real_s_sizeleft;
  158.  
  159. /*
  160.  * Return the location of the next available input or output record.
  161.  * Return NULL for EOF.  Once we have returned NULL, we just keep returning
  162.  * it, to avoid accidentally going on to the next file on the "tape".
  163.  */
  164. union record *
  165. findrec()
  166. {
  167.     if (ar_record == ar_last) {
  168.         if (eof)
  169.             return (union record *)NULL;    /* EOF */
  170.         flush_archive();
  171.         if (ar_record == ar_last) {
  172.             eof++;
  173.             return (union record *)NULL;    /* EOF */
  174.         }
  175.     }
  176.     return ar_record;
  177. }
  178.  
  179.  
  180. /*
  181.  * Indicate that we have used all records up thru the argument.
  182.  * (should the arg have an off-by-1? XXX FIXME)
  183.  */
  184. void
  185. userec(rec)
  186.     union record *rec;
  187. {
  188.     while(rec >= ar_record)
  189.         ar_record++;
  190.     /*
  191.      * Do NOT flush the archive here.  If we do, the same
  192.      * argument to userec() could mean the next record (if the
  193.      * input block is exactly one record long), which is not what
  194.      * is intended.
  195.      */
  196.     if (ar_record > ar_last)
  197.         abort();
  198. }
  199.  
  200.  
  201. /*
  202.  * Return a pointer to the end of the current records buffer.
  203.  * All the space between findrec() and endofrecs() is available
  204.  * for filling with data, or taking data from.
  205.  */
  206. union record *
  207. endofrecs()
  208. {
  209.     return ar_last;
  210. }
  211.  
  212.  
  213. /*
  214.  * Duplicate a file descriptor into a certain slot.
  215.  * Equivalent to BSD "dup2" with error reporting.
  216.  */
  217. void
  218. dupto(from, to, msg)
  219.     int from, to;
  220.     char *msg;
  221. {
  222.     int err;
  223.  
  224.     if (from != to) {
  225.         err=close(to);
  226.         if(err<0 && errno!=EBADF) {
  227.             msg_perror("Cannot close descriptor %d",to);
  228.             exit(EX_SYSTEM);
  229.         }
  230.         err = dup(from);
  231.         if (err != to) {
  232.             msg_perror("cannot dup %s",msg);
  233.             exit(EX_SYSTEM);
  234.         }
  235.         ck_close(from);
  236.     }
  237. }
  238.  
  239. #ifdef MSDOS
  240. void
  241. child_open()
  242. {
  243.     fprintf(stderr,"MSDOS %s can't use compressed or remote archives\n",tar);
  244.     exit(EX_ARGSBAD);
  245. }
  246. #else
  247. void
  248. child_open()
  249. {
  250.     int pipe[2];
  251.     int err = 0;
  252.  
  253.     int kidpipe[2];
  254.     int kidchildpid;
  255.  
  256. #define READ    0
  257. #define WRITE    1
  258.  
  259.     ck_pipe(pipe);
  260.  
  261.     childpid=fork();
  262.     if(childpid<0) {
  263.         msg_perror("cannot fork");
  264.         exit(EX_SYSTEM);
  265.     }
  266.     if(childpid>0) {
  267.         /* We're the parent.  Clean up and be happy */
  268.         /* This, at least, is easy */
  269.  
  270.         if(ar_reading) {
  271.             f_reblock++;
  272.             archive=pipe[READ];
  273.             ck_close(pipe[WRITE]);
  274.         } else {
  275.             archive = pipe[WRITE];
  276.             ck_close(pipe[READ]);
  277.         }
  278.         return;
  279.     }
  280.  
  281.     /* We're the kid */
  282.     if(ar_reading) {
  283.         dupto(pipe[WRITE],STDOUT,"(child) pipe to stdout");
  284.         ck_close(pipe[READ]);
  285.     } else {
  286.         dupto(pipe[READ],STDIN,"(child) pipe to stdin");
  287.         ck_close(pipe[WRITE]);
  288.     }
  289.  
  290.     /* We need a child tar only if
  291.        1: we're reading/writing stdin/out (to force reblocking)
  292.        2: the file is to be accessed by rmt (compress doesn't know how)
  293.        3: the file is not a plain file */
  294. #ifdef NO_REMOTE
  295.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && isfile(ar_file))
  296. #else
  297.     if(!(ar_file[0]=='-' && ar_file[1]=='\0') && !_remdev(ar_file) && isfile(ar_file))
  298. #endif
  299.     {
  300.         /* We don't need a child tar.  Open the archive */
  301.         if(ar_reading) {
  302.             archive=open(ar_file, O_RDONLY|O_BINARY, 0666);
  303.             if(archive<0) {
  304.                 msg_perror("can't open archive %s",ar_file);
  305.                 exit(EX_BADARCH);
  306.             }
  307.             dupto(archive,STDIN,"archive to stdin");
  308.             /* close(archive); */
  309.         } else {
  310.             archive=creat(ar_file,0666);
  311.             if(archive<0) {
  312.                 msg_perror("can't open archive %s",ar_file);
  313.                 exit(EX_BADARCH);
  314.             }
  315.             dupto(archive,STDOUT,"archive to stdout");
  316.             /* close(archive); */
  317.         }
  318.     } else {
  319.         /* We need a child tar */
  320.         ck_pipe(kidpipe);
  321.  
  322.         kidchildpid=fork();
  323.         if(kidchildpid<0) {
  324.             msg_perror("child can't fork");
  325.             exit(EX_SYSTEM);
  326.         }
  327.  
  328.         if(kidchildpid>0) {
  329.             /* About to exec compress:  set up the files */
  330.             if(ar_reading) {
  331.                 dupto(kidpipe[READ],STDIN,"((child)) pipe to stdin");
  332.                 ck_close(kidpipe[WRITE]);
  333.                 /* dup2(pipe[WRITE],STDOUT); */
  334.             } else {
  335.                 /* dup2(pipe[READ],STDIN); */
  336.                 dupto(kidpipe[WRITE],STDOUT,"((child)) pipe to stdout");
  337.                 ck_close(kidpipe[READ]);
  338.             }
  339.             /* ck_close(pipe[READ]); */
  340.             /* ck_close(pipe[WRITE]); */
  341.             /* ck_close(kidpipe[READ]);
  342.             ck_close(kidpipe[WRITE]); */
  343.         } else {
  344.         /* Grandchild.  Do the right thing, namely sit here and
  345.            read/write the archive, and feed stuff back to compress */
  346.             tar="tar (child)";
  347.             if(ar_reading) {
  348.                 dupto(kidpipe[WRITE],STDOUT,"[child] pipe to stdout");
  349.                 ck_close(kidpipe[READ]);
  350.             } else {
  351.                 dupto(kidpipe[READ],STDIN,"[child] pipe to stdin");
  352.                 ck_close(kidpipe[WRITE]);
  353.             }
  354.  
  355.             if (ar_file[0] == '-' && ar_file[1] == '\0') {
  356.                 if (ar_reading)
  357.                     archive = STDIN;
  358.                 else
  359.                     archive = STDOUT;
  360.             } else /* This can't happen if (ar_reading==2)
  361.                 archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  362.             else */if(ar_reading)
  363.                 archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  364.             else
  365.                 archive = rmtcreat(ar_file, 0666);
  366.  
  367.             if (archive < 0) {
  368.                 msg_perror("can't open archive %s",ar_file);
  369.                 exit(EX_BADARCH);
  370.             }
  371.  
  372.             if(ar_reading) {
  373.                 for(;;) {
  374.                     char *ptr;
  375.                     int max,count;
  376.         
  377.                     r_error_count = 0;
  378.                 error_loop:
  379.                     err=rmtread(archive, ar_block->charptr,(int)(blocksize));
  380.                     if(err<0) {
  381.                         readerror();
  382.                         goto error_loop;
  383.                     }
  384.                     if(err==0)
  385.                         break;
  386.                     ptr = ar_block->charptr;
  387.                     max = err;
  388.                     while(max) {
  389.                         count = (max<RECORDSIZE) ? max : RECORDSIZE;
  390.                         err=write(STDOUT,ptr,count);
  391.                         if(err!=count) {
  392.                             if(err<0) {
  393.                                 msg_perror("can't write to compress");
  394.                                 exit(EX_SYSTEM);
  395.                             } else
  396.                                 msg("write to compress short %d bytes",count-err);
  397.                             count = (err<0) ? 0 : err;
  398.                         }
  399.                         ptr+=count;
  400.                         max-=count;
  401.                     }
  402.                 }
  403.             } else {
  404.                 for(;;) {
  405.                     int n;
  406.                     char *ptr;
  407.         
  408.                     n=blocksize;
  409.                     ptr = ar_block->charptr;
  410.                     while(n) {
  411.                         err=read(STDIN,ptr,(n<RECORDSIZE) ? n : RECORDSIZE);
  412.                         if(err<=0)
  413.                             break;
  414.                         n-=err;
  415.                         ptr+=err;
  416.                     }
  417.                         /* EOF */
  418.                     if(err==0) {
  419.                         if(f_compress<2)
  420.                             blocksize-=n;
  421.                         else
  422.                             bzero(ar_block->charptr+n,blocksize-n);
  423.                         err=rmtwrite(archive,ar_block->charptr,blocksize);
  424.                         if(err!=(blocksize))
  425.                             writeerror(err);
  426.                         if(f_compress<2)
  427.                             blocksize+=n;
  428.                         break;
  429.                     }
  430.                     if(n) {
  431.                         msg_perror("can't read from compress");
  432.                         exit(EX_SYSTEM);
  433.                     }
  434.                     err=rmtwrite(archive, ar_block->charptr, (int)blocksize);
  435.                     if(err!=blocksize)
  436.                         writeerror(err);
  437.                 }
  438.             }
  439.         
  440.             /* close_archive(); */
  441.             exit(0);
  442.         }
  443.     }
  444.         /* So we should exec compress (-d) */
  445.     if(ar_reading)
  446.         execlp("compress", "compress", "-d", (char *)0);
  447.     else
  448.         execlp("compress", "compress", (char *)0);
  449.     msg_perror("can't exec compress");
  450.     _exit(EX_SYSTEM);
  451. }
  452.  
  453.  
  454. /* return non-zero if p is the name of a directory */
  455. isfile(p)
  456. char *p;
  457. {
  458.     struct stat stbuf;
  459.  
  460.     if(stat(p,&stbuf)<0)
  461.         return 1;
  462.     if((stbuf.st_mode&S_IFMT)==S_IFREG)
  463.         return 1;
  464.     return 0;
  465. }
  466.  
  467. #endif
  468.  
  469. /*
  470.  * Open an archive file.  The argument specifies whether we are
  471.  * reading or writing.
  472.  */
  473. /* JF if the arg is 2, open for reading and writing. */
  474. open_archive(reading)
  475.     int reading;
  476. {
  477.     msg_file = stdout;
  478.  
  479.     if (blocksize == 0) {
  480.         msg("invalid value for blocksize");
  481.         exit(EX_ARGSBAD);
  482.     }
  483.  
  484.     if(ar_file==0) {
  485.         msg("No archive name given, what should I do?");
  486.         exit(EX_BADARCH);
  487.     }
  488.  
  489.     /*NOSTRICT*/
  490.     if(f_multivol) {
  491.         ar_block = (union record *) valloc((unsigned)(blocksize+(2*RECORDSIZE)));
  492.         if(ar_block)
  493.             ar_block += 2;
  494.     } else
  495.         ar_block = (union record *) valloc((unsigned)blocksize);
  496.     if (!ar_block) {
  497.         msg("could not allocate memory for blocking factor %d",
  498.             blocking);
  499.         exit(EX_ARGSBAD);
  500.     }
  501.  
  502.     ar_record = ar_block;
  503.     ar_last   = ar_block + blocking;
  504.     ar_reading = reading;
  505.  
  506.     if (f_compress) {
  507.         if(reading==2 || f_verify) {
  508.             msg("cannot update or verify compressed archives");
  509.             exit(EX_ARGSBAD);
  510.         }
  511.         child_open();
  512.         if(!reading && ar_file[0]=='-' && ar_file[1]=='\0')
  513.             msg_file = stderr;
  514.         /* child_open(rem_host, rem_file); */
  515.     } else if (ar_file[0] == '-' && ar_file[1] == '\0') {
  516.         f_reblock++;    /* Could be a pipe, be safe */
  517.         if(f_verify) {
  518.             msg("can't verify stdin/stdout archive");
  519.             exit(EX_ARGSBAD);
  520.         }
  521.         if(reading==2) {
  522.             archive=STDIN;
  523.             msg_file=stderr;
  524.             write_archive_to_stdout++;
  525.         } else if (reading)
  526.             archive = STDIN;
  527.         else {
  528.             archive = STDOUT;
  529.             msg_file = stderr;
  530.         }
  531.     } else if (reading==2 || f_verify) {
  532.         archive = rmtopen(ar_file, O_RDWR|O_CREAT|O_BINARY, 0666);
  533.     } else if(reading) {
  534.         archive = rmtopen(ar_file, O_RDONLY|O_BINARY, 0666);
  535.     } else {
  536.         archive = rmtcreat(ar_file, 0666);
  537.     }
  538.  
  539.     if (archive < 0) {
  540.         msg_perror("can't open %s",ar_file);
  541.         exit(EX_BADARCH);
  542.     }
  543. #ifdef    MSDOS
  544.     setmode(archive, O_BINARY);
  545. #endif
  546.  
  547.     if (reading) {
  548.         ar_last = ar_block;        /* Set up for 1st block = # 0 */
  549.         (void) findrec();        /* Read it in, check for EOF */
  550.  
  551.         if(f_volhdr) {
  552.             union record *head;
  553.             char *ptr;
  554.  
  555.             if(f_multivol) {
  556.                 ptr=malloc(strlen(f_volhdr)+20);
  557.                 sprintf(ptr,"%s Volume %d",f_volhdr,1);
  558.             } else
  559.                 ptr=f_volhdr;
  560.             head=findrec();
  561.             if(!head)
  562.                 exit(EX_BADARCH);
  563.             if(strcmp(ptr,head->header.name)) {
  564.                 msg("Volume mismatch!  %s!=%s\n",ptr,head->header.name);
  565.                 exit(EX_BADARCH);
  566.             }
  567.             if(ptr!=f_volhdr)
  568.                 free(ptr);
  569.         }
  570.     } else if(f_volhdr) {
  571.         bzero((void *)ar_block,RECORDSIZE);
  572.         if(f_multivol)
  573.             sprintf(ar_block->header.name,"%s Volume 1",f_volhdr);
  574.         else
  575.             strcpy(ar_block->header.name,f_volhdr);
  576.         ar_block->header.linkflag = LF_VOLHDR;
  577.         finish_header(ar_block);
  578.         /* ar_record++; */
  579.     }
  580. }
  581.  
  582.  
  583. /*
  584.  * Remember a union record * as pointing to something that we
  585.  * need to keep when reading onward in the file.  Only one such
  586.  * thing can be remembered at once, and it only works when reading
  587.  * an archive.
  588.  *
  589.  * We calculate "offset" then add it because some compilers end up
  590.  * adding (baserec+ar_record), doing a 9-bit shift of baserec, then
  591.  * subtracting ar_block from that, shifting it back, losing the top 9 bits.
  592.  */
  593. saverec(pointer)
  594.     union record **pointer;
  595. {
  596.     long offset;
  597.  
  598.     save_rec = pointer;
  599.     offset = ar_record - ar_block;
  600.     saved_recno = baserec + offset;
  601. }
  602.  
  603. /*
  604.  * Perform a write to flush the buffer.
  605.  */
  606.  
  607. /*send_buffer_to_file();
  608.   if(new_volume) {
  609.       deal_with_new_volume_stuff();
  610.     send_buffer_to_file();
  611.   }
  612.  */
  613.  
  614. fl_write()
  615. {
  616.     int err;
  617.     int copy_back;
  618. #ifdef TEST
  619.     static long test_written = 0;
  620. #endif
  621.  
  622. #ifdef TEST
  623.     if(test_written>=30720) {
  624.         errno = ENOSPC;
  625.         err = 0;
  626.     } else
  627. #endif
  628.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  629.     if(err!=blocksize && !f_multivol)
  630.         writeerror(err);
  631.  
  632. #ifdef TEST
  633.     if(err>0)
  634.         test_written+=err;
  635. #endif
  636.     if (err == blocksize) {
  637.         if(f_multivol) {
  638.             if(!save_name) {
  639.                 real_s_name[0]='\0';
  640.                 real_s_totsize=0;
  641.                 real_s_sizeleft = 0;
  642.                 return;
  643.             }
  644. #ifdef MSDOS
  645.             if(save_name[1]==':')
  646.                 save_name+=2;
  647. #endif
  648.             while(*save_name=='/')
  649.                 save_name++;
  650.  
  651.             strcpy(real_s_name,save_name);
  652.             real_s_totsize = save_totsize;
  653.             real_s_sizeleft = save_sizeleft;
  654.         }
  655.         return;
  656.     }
  657.  
  658.     /* We're multivol  Panic if we didn't get the right kind of response */
  659.     /* ENXIO is for the UNIX PC */
  660.     if(err>0 || (err<0 && errno!=ENOSPC && errno!=EIO && errno!=ENXIO))
  661.         writeerror(err);
  662.  
  663.     if(new_volume(0)<0)
  664.         return;
  665. #ifdef TEST
  666.     test_written=0;
  667. #endif
  668.     if(f_volhdr && real_s_name[0]) {
  669.         copy_back=2;
  670.         ar_block-=2;
  671.     } else if(f_volhdr || real_s_name[0]) {
  672.         copy_back = 1;
  673.         ar_block--;
  674.     } else
  675.         copy_back = 0;
  676.     if(f_volhdr) {
  677.         bzero((void *)ar_block,RECORDSIZE);
  678.         sprintf(ar_block->header.name,"%s Volume %d",f_volhdr,volno);
  679.         ar_block->header.linkflag = LF_VOLHDR;
  680.         finish_header(ar_block);
  681.     }
  682.     if(real_s_name[0]) {
  683.         extern void to_oct();
  684.         int tmp;
  685.  
  686.         if(f_volhdr)
  687.             ar_block++;
  688.         bzero((void *)ar_block,RECORDSIZE);
  689.         strcpy(ar_block->header.name,real_s_name);
  690.         ar_block->header.linkflag = LF_MULTIVOL;
  691.         to_oct((long)real_s_sizeleft,1+12,
  692.                ar_block->header.size);
  693.         to_oct((long)real_s_totsize-real_s_sizeleft,
  694.                1+12,ar_block->header.offset);
  695.         tmp=f_verbose;
  696.         f_verbose=0;
  697.         finish_header(ar_block);
  698.         f_verbose=tmp;
  699.         if(f_volhdr)
  700.             ar_block--;
  701.     }
  702.  
  703.     err = rmtwrite(archive, ar_block->charptr,(int) blocksize);
  704.     if(err!=blocksize)
  705.         writeerror(err);
  706.  
  707. #ifdef TEST
  708.     test_written = blocksize;
  709. #endif
  710.     if(copy_back) {
  711.         ar_block+=copy_back;
  712.         bcopy((void *)(ar_block+blocking-copy_back),
  713.               (void *)ar_record,
  714.               copy_back*RECORDSIZE);
  715.         ar_record+=copy_back;
  716.  
  717.         if(real_s_sizeleft>=copy_back*RECORDSIZE)
  718.             real_s_sizeleft-=copy_back*RECORDSIZE;
  719.         else if((real_s_sizeleft+RECORDSIZE-1)/RECORDSIZE<=copy_back)
  720.             real_s_name[0] = '\0';
  721.         else {
  722. #ifdef MSDOS
  723.             if(save_name[1]==':')
  724.                 save_name+=2;
  725. #endif
  726.             while(*save_name=='/')
  727.                 save_name++;
  728.  
  729.             strcpy(real_s_name,save_name);
  730.             real_s_sizeleft = save_sizeleft;
  731.             real_s_totsize=save_totsize;
  732.         }
  733.         copy_back = 0;
  734.     }
  735. }
  736.  
  737. /* Handle write errors on the archive.  Write errors are always fatal */
  738. /* Hitting the end of a volume does not cause a write error unless the write
  739. *  was the first block of the volume */
  740.  
  741. void
  742. writeerror(err)
  743. int err;
  744. {
  745.     if (err < 0) {
  746.         msg_perror("can't write to %s",ar_file);
  747.         exit(EX_BADARCH);
  748.     } else {
  749.         msg("only wrote %u of %u bytes to %s",err,blocksize,ar_file);
  750.         exit(EX_BADARCH);
  751.     }
  752. }
  753.  
  754. /*
  755.  * Handle read errors on the archive.
  756.  *
  757.  * If the read should be retried, readerror() returns to the caller.
  758.  */
  759. void
  760. readerror()
  761. {
  762. #    define    READ_ERROR_MAX    10
  763.  
  764.     read_error_flag++;        /* Tell callers */
  765.  
  766.     msg_perror("read error on %s",ar_file);
  767.  
  768.     if (baserec == 0) {
  769.         /* First block of tape.  Probably stupidity error */
  770.         exit(EX_BADARCH);
  771.     }
  772.  
  773.     /*
  774.      * Read error in mid archive.  We retry up to READ_ERROR_MAX times
  775.      * and then give up on reading the archive.  We set read_error_flag
  776.      * for our callers, so they can cope if they want.
  777.      */
  778.     if (r_error_count++ > READ_ERROR_MAX) {
  779.         msg("Too many errors, quitting.");
  780.         exit(EX_BADARCH);
  781.     }
  782.     return;
  783. }
  784.  
  785.  
  786. /*
  787.  * Perform a read to flush the buffer.
  788.  */
  789. fl_read()
  790. {
  791.     int err;        /* Result from system call */
  792.     int left;        /* Bytes left */
  793.     char *more;        /* Pointer to next byte to read */
  794.  
  795.     /*
  796.      * Clear the count of errors.  This only applies to a single
  797.      * call to fl_read.  We leave read_error_flag alone; it is
  798.      * only turned off by higher level software.
  799.      */
  800.     r_error_count = 0;    /* Clear error count */
  801.  
  802.     /*
  803.      * If we are about to wipe out a record that
  804.      * somebody needs to keep, copy it out to a holding
  805.      * area and adjust somebody's pointer to it.
  806.      */
  807.     if (save_rec &&
  808.         *save_rec >= ar_record &&
  809.         *save_rec < ar_last) {
  810.         record_save_area = **save_rec;
  811.         *save_rec = &record_save_area;
  812.     }
  813.     if(write_archive_to_stdout && baserec!=0) {
  814.         err=rmtwrite(1, ar_block->charptr, blocksize);
  815.         if(err!=blocksize)
  816.             writeerror(err);
  817.     }
  818.     if(f_multivol) {
  819.         if(save_name) {
  820.             if(save_name!=real_s_name) {
  821. #ifdef MSDOS
  822.                 if(save_name[1]==':')
  823.                     save_name+=2;
  824. #endif
  825.                 while(*save_name=='/')
  826.                     save_name++;
  827.  
  828.                 strcpy(real_s_name,save_name);
  829.                 save_name=real_s_name;
  830.             }
  831.             real_s_totsize = save_totsize;
  832.             real_s_sizeleft = save_sizeleft;
  833.                 
  834.         } else {
  835.             real_s_name[0]='\0';
  836.             real_s_totsize=0;
  837.             real_s_sizeleft = 0;
  838.         }
  839.     }
  840.  
  841. error_loop:
  842.     err = rmtread(archive, ar_block->charptr, (int)blocksize);
  843.     if (err == blocksize)
  844.         return;
  845.  
  846.     if((err == 0 || (err<0 && errno==ENOSPC)) && f_multivol) {
  847.         union record *head;
  848.  
  849.     try_volume:
  850.         if(new_volume((cmd_mode==CMD_APPEND || cmd_mode==CMD_CAT || cmd_mode==CMD_UPDATE) ? 2 : 1)<0)
  851.             return;
  852.     vol_error:
  853.         err = rmtread(archive, ar_block->charptr,(int) blocksize);
  854.         if(err < 0) {
  855.             readerror();
  856.             goto vol_error;
  857.         }
  858.         if(err!=blocksize)
  859.             goto short_read;
  860.  
  861.         head=ar_block;
  862.  
  863.         if(head->header.linkflag==LF_VOLHDR) {
  864.             if(f_volhdr) {
  865.                 char *ptr;
  866.  
  867.                 ptr=(char *)malloc(strlen(f_volhdr)+20);
  868.                 sprintf(ptr,"%s Volume %d",f_volhdr,volno);
  869.                  if(strcmp(ptr,head->header.name)) {
  870.                     msg("Volume mismatch! %s!=%s\n",ptr,head->header.name);
  871.                     --volno;
  872.                     free(ptr);
  873.                     goto try_volume;
  874.                 }
  875.                 free(ptr);
  876.             }
  877.             if(f_verbose)
  878.                 fprintf(msg_file,"Reading %s\n",head->header.name);
  879.             head++;
  880.         } else if(f_volhdr) {
  881.             msg("Warning:  No volume header!");
  882.         }
  883.  
  884.         if(real_s_name[0]) {
  885.             long from_oct();
  886.  
  887.             if(head->header.linkflag!=LF_MULTIVOL || strcmp(head->header.name,real_s_name)) {
  888.                 msg("%s is not continued on this volume!",real_s_name);
  889.                 --volno;
  890.                 goto try_volume;
  891.             }
  892.             if(real_s_totsize!=from_oct(1+12,head->header.size)+from_oct(1+12,head->header.offset)) {
  893.                 msg("%s is the wrong size (%ld!=%ld+%ld)",
  894.                        head->header.name,save_totsize,
  895.                        from_oct(1+12,head->header.size),
  896.                        from_oct(1+12,head->header.offset));
  897.                 --volno;
  898.                 goto try_volume;
  899.             }
  900.             if(real_s_totsize-real_s_sizeleft!=from_oct(1+12,head->header.offset)) {
  901.                 msg("This volume is out of sequence");
  902.                 --volno;
  903.                 goto try_volume;
  904.             }
  905.             head++;
  906.         }
  907.         ar_record=head;
  908.         return;
  909.     } else if (err < 0) {
  910.         readerror();
  911.         goto error_loop;    /* Try again */
  912.     }
  913.  
  914.  short_read:
  915.     more = ar_block->charptr + err;
  916.     left = blocksize - err;
  917.  
  918. again:
  919.     if (0 == (((unsigned)left) % RECORDSIZE)) {
  920.         /* FIXME, for size=0, multi vol support */
  921.         /* On the first block, warn about the problem */
  922.         if (!f_reblock && baserec == 0 && f_verbose && err > 0) {
  923.         /*    msg("Blocksize = %d record%s",
  924.                 err / RECORDSIZE, (err > RECORDSIZE)? "s": "");*/
  925.             msg("Blocksize = %d records", err / RECORDSIZE);
  926.         }
  927.         ar_last = ar_block + ((unsigned)(blocksize - left))/RECORDSIZE;
  928.         return;
  929.     }
  930.     if (f_reblock) {
  931.         /*
  932.          * User warned us about this.  Fix up.
  933.          */
  934.         if (left > 0) {
  935. error2loop:
  936.             err = rmtread(archive, more, (int)left);
  937.             if (err < 0) {
  938.                 readerror();
  939.                 goto error2loop;    /* Try again */
  940.             }
  941.             if (err == 0) {
  942.                 msg("archive %s EOF not on block boundary",ar_file);
  943.                 exit(EX_BADARCH);
  944.             }
  945.             left -= err;
  946.             more += err;
  947.             goto again;
  948.         }
  949.     } else {
  950.         msg("only read %d bytes from archive %s",err,ar_file);
  951.         exit(EX_BADARCH);
  952.     }
  953. }
  954.  
  955.  
  956. /*
  957.  * Flush the current buffer to/from the archive.
  958.  */
  959. flush_archive()
  960. {
  961.     baserec += ar_last - ar_block;    /* Keep track of block #s */
  962.     ar_record = ar_block;        /* Restore pointer to start */
  963.     ar_last = ar_block + blocking;    /* Restore pointer to end */
  964.  
  965.     if (ar_reading) {
  966.         if(time_to_start_writing) {
  967.             time_to_start_writing=0;
  968.             ar_reading=0;
  969.  
  970.             if(file_to_switch_to>=0) {
  971.                 rmtclose(archive);
  972.                 archive=file_to_switch_to;
  973.             } else
  974.                  (void)backspace_output();
  975.             fl_write();
  976.         } else
  977.             fl_read();
  978.     } else {
  979.         fl_write();
  980.     }
  981. }
  982.  
  983. /* Backspace the archive descriptor by one blocks worth.
  984.    If its a tape, MTIOCTOP will work.  If its something else,
  985.    we try to seek on it.  If we can't seek, we lose! */
  986. backspace_output()
  987. {
  988.     long cur;
  989.     /* int er; */
  990.     extern char *output_start;
  991.  
  992. #ifdef MTIOCTOP
  993.     struct mtop t;
  994.  
  995.     t.mt_op = MTBSR;
  996.     t.mt_count = 1;
  997.     if((rmtioctl(archive,MTIOCTOP,&t))>=0)
  998.         return 1;
  999.     if(errno==EIO && (rmtioctl(archive,MTIOCTOP,&t))>=0)
  1000.         return 1;
  1001. #endif
  1002.  
  1003.         cur=rmtlseek(archive,0L,1);
  1004.     cur-=blocksize;
  1005.     /* Seek back to the beginning of this block and
  1006.        start writing there. */
  1007.  
  1008.     if(rmtlseek(archive,cur,0)!=cur) {
  1009.         /* Lseek failed.  Try a different method */
  1010.         msg("Couldn't backspace archive file.  It may be unreadable without -i.");
  1011.         /* Replace the first part of the block with nulls */
  1012.         if(ar_block->charptr!=output_start)
  1013.             bzero(ar_block->charptr,output_start-ar_block->charptr);
  1014.         return 2;
  1015.     }
  1016.     return 3;
  1017. }
  1018.  
  1019.  
  1020. /*
  1021.  * Close the archive file.
  1022.  */
  1023. close_archive()
  1024. {
  1025.     int child;
  1026.     int status;
  1027.  
  1028.     if (time_to_start_writing || !ar_reading)
  1029.         flush_archive();
  1030.     if(cmd_mode==CMD_DELETE) {
  1031.         long pos;
  1032.  
  1033.         pos = rmtlseek(archive,0L,1);
  1034. #ifndef MSDOS
  1035.         /* FIXME does ftruncate really take an INT?! */
  1036.         (void) ftruncate(archive,(int)pos);
  1037. #else
  1038.         (void)rmtwrite(archive,"",0);
  1039. #endif
  1040.     }
  1041.     if(f_verify)
  1042.         verify_volume();
  1043.     (void) rmtclose(archive);
  1044.  
  1045. #ifndef    MSDOS
  1046.     if (childpid) {
  1047.         /*
  1048.          * Loop waiting for the right child to die, or for
  1049.          * no more kids.
  1050.          */
  1051.         while (((child = wait(&status)) != childpid) && child != -1)
  1052.             ;
  1053.  
  1054.         if (child != -1) {
  1055.             switch (TERM_SIGNAL(status)) {
  1056.             case 0:
  1057.                 /* Child voluntarily terminated  -- but why? */
  1058.                 if (TERM_VALUE(status) == MAGIC_STAT) {
  1059.                     exit(EX_SYSTEM);/* Child had trouble */
  1060.                 }
  1061.                 if (TERM_VALUE(status) == (SIGPIPE + 128)) {
  1062.                     /*
  1063.                      * /bin/sh returns this if its child
  1064.                      * dies with SIGPIPE.  'Sok.
  1065.                      */
  1066.                     break;
  1067.                 } else if (TERM_VALUE(status))
  1068.                     msg("child returned status %d",
  1069.                         TERM_VALUE(status));
  1070.             case SIGPIPE:
  1071.                 break;        /* This is OK. */
  1072.  
  1073.             default:
  1074.                 msg("child died with signal %d%s",
  1075.                  TERM_SIGNAL(status),
  1076.                  TERM_COREDUMP(status)? " (core dumped)": "");
  1077.             }
  1078.         }
  1079.     }
  1080. #endif    /* MSDOS */
  1081. }
  1082.  
  1083.  
  1084. #ifdef DONTDEF
  1085. /*
  1086.  * Message management.
  1087.  *
  1088.  * anno writes a message prefix on stream (eg stdout, stderr).
  1089.  *
  1090.  * The specified prefix is normally output followed by a colon and a space.
  1091.  * However, if other command line options are set, more output can come
  1092.  * out, such as the record # within the archive.
  1093.  *
  1094.  * If the specified prefix is NULL, no output is produced unless the
  1095.  * command line option(s) are set.
  1096.  *
  1097.  * If the third argument is 1, the "saved" record # is used; if 0, the
  1098.  * "current" record # is used.
  1099.  */
  1100. void
  1101. anno(stream, prefix, savedp)
  1102.     FILE    *stream;
  1103.     char    *prefix;
  1104.     int    savedp;
  1105. {
  1106. #    define    MAXANNO    50
  1107.     char    buffer[MAXANNO];    /* Holds annorecment */
  1108. #    define    ANNOWIDTH 13
  1109.     int    space;
  1110.     long    offset;
  1111.     int    save_e;
  1112.  
  1113.     save_e=errno;
  1114.     /* Make sure previous output gets out in sequence */
  1115.     if (stream == stderr)
  1116.         fflush(stdout);
  1117.     if (f_sayblock) {
  1118.         if (prefix) {
  1119.             fputs(prefix, stream);
  1120.             putc(' ', stream);
  1121.         }
  1122.         offset = ar_record - ar_block;
  1123.         (void) sprintf(buffer, "rec %d: ",
  1124.             savedp?    saved_recno:
  1125.                 baserec + offset);
  1126.         fputs(buffer, stream);
  1127.         space = ANNOWIDTH - strlen(buffer);
  1128.         if (space > 0) {
  1129.             fprintf(stream, "%*s", space, "");
  1130.         }
  1131.     } else if (prefix) {
  1132.         fputs(prefix, stream);
  1133.         fputs(": ", stream);
  1134.     }
  1135.     errno=save_e;
  1136. }
  1137. #endif
  1138.  
  1139. /* We've hit the end of the old volume.  Close it and open the next one */
  1140. /* Values for type:  0: writing  1: reading  2: updating */
  1141. new_volume(type)
  1142. int    type;
  1143. {
  1144.     /* int    c; */
  1145.     char    inbuf[80];
  1146.     char    *p;
  1147.     static FILE *read_file = 0;
  1148.     extern int now_verifying;
  1149.     extern char TTY_NAME[];
  1150.     char *getenv();
  1151.  
  1152.     if(!read_file && !f_run_script_at_end)
  1153.         read_file = (archive==0) ? fopen(TTY_NAME, "r") : stdin;
  1154.  
  1155.     if(now_verifying)
  1156.         return -1;
  1157.     if(f_verify)
  1158.         verify_volume();
  1159.     if(rmtclose(archive)<0) {
  1160.         msg_perror("can't close %s",ar_file);
  1161.         exit(EX_BADARCH);
  1162.     }
  1163.     volno++;
  1164.     if (f_run_script_at_end)
  1165.         system(info_script);
  1166.     else for(;;) {
  1167.         fprintf(msg_file,"Prepare volume #%d and hit return: ",volno);
  1168.         if(fgets(inbuf,sizeof(inbuf),read_file)==0 || inbuf[0]=='\n')
  1169.             break;
  1170.         switch(inbuf[0]) {
  1171.         case '?':
  1172.         {
  1173.             fprintf(msg_file,"\
  1174.  n [name]   Give a new filename for the next (and subsequent) volume(s)\n\
  1175.  q          Abort tar\n\
  1176.  !          Spawn a subshell\n\
  1177.  ?          Print this list\n");
  1178.         }
  1179.             break;
  1180.  
  1181.         case 'q':    /* Quit */
  1182.             fprintf(msg_file,"No new volume; exiting.\n");
  1183.             if(cmd_mode!=CMD_EXTRACT && cmd_mode!=CMD_LIST && cmd_mode!=CMD_DIFF)
  1184.                 msg("Warning:  Archive is INCOMPLETE!");
  1185.             exit(EX_BADARCH);
  1186.  
  1187.         case 'n':    /* Get new file name */
  1188.         {
  1189.             char *q,*r;
  1190.             static char *old_name;
  1191.  
  1192.             for(q= &inbuf[1];*q==' ' || *q=='\t';q++)
  1193.                 ;
  1194.             for(r=q;*r;r++)
  1195.                 if(*r=='\n')
  1196.                     *r='\0';
  1197.             if(old_name)
  1198.                 free(old_name);
  1199.             old_name=p=(char *)malloc((unsigned)(strlen(q)+2));
  1200.             if(p==0) {
  1201.                 msg("Can't allocate memory for name");
  1202.                 exit(EX_SYSTEM);
  1203.             }
  1204.             (void) strcpy(p,q);
  1205.             ar_file=p;
  1206.         }
  1207.             break;
  1208.  
  1209.         case '!':
  1210. #ifdef MSDOS
  1211.             spawnl(P_WAIT,getenv("COMSPEC"),"-",0);
  1212. #else
  1213.                 /* JF this needs work! */
  1214.             switch(fork()) {
  1215.             case -1:
  1216.                 msg_perror("can't fork!");
  1217.                 break;
  1218.             case 0:
  1219.                 p=getenv("SHELL");
  1220.                 if(p==0) p="/bin/sh";
  1221.                 execlp(p,"-sh","-i",0);
  1222.                 msg_perror("can't exec a shell %s",p);
  1223.                 _exit(55);
  1224.             default:
  1225.                 wait(0);
  1226.                 break;
  1227.             }
  1228. #endif
  1229.             break;
  1230.         }
  1231.     }
  1232.  
  1233.     if(type==2 || f_verify)
  1234.         archive=rmtopen(ar_file,O_RDWR|O_CREAT,0666);
  1235.     else if(type==1)
  1236.         archive=rmtopen(ar_file,O_RDONLY,0666);
  1237.     else if(type==0)
  1238.         archive=rmtcreat(ar_file,0666);
  1239.     else
  1240.         archive= -1;
  1241.  
  1242.     if(archive<0) {
  1243.         msg_perror("can't open %s",ar_file);
  1244.         exit(EX_BADARCH);
  1245.     }
  1246. #ifdef MSDOS
  1247.     setmode(archive,O_BINARY);
  1248. #endif
  1249.     return 0;
  1250. }
  1251.  
  1252. /* this is a useless function that takes a buffer returned by wantbytes
  1253.    and does nothing with it.  If the function called by wantbytes returns
  1254.    an error indicator (non-zero), this function is called for the rest of
  1255.    the file.
  1256.  */
  1257. int
  1258. no_op(size,data)
  1259. int size;
  1260. char *data;
  1261. {
  1262.     return 0;
  1263. }
  1264.  
  1265. /* Some other routine wants SIZE bytes in the archive.  For each chunk of
  1266.    the archive, call FUNC with the size of the chunk, and the address of
  1267.    the chunk it can work with.
  1268.  */
  1269. int
  1270. wantbytes(size,func)
  1271. long size;
  1272. int (*func)();
  1273. {
  1274.     char *data;
  1275.     long    data_size;
  1276.  
  1277.     while(size) {
  1278.         data = findrec()->charptr;
  1279.         if (data == NULL) {    /* Check it... */
  1280.             msg("Unexpected EOF on archive file");
  1281.             return -1;
  1282.         }
  1283.         data_size = endofrecs()->charptr - data;
  1284.         if(data_size>size)
  1285.             data_size=size;
  1286.         if((*func)(data_size,data))
  1287.             func=no_op;
  1288.         userec((union record *)(data + data_size - 1));
  1289.         size-=data_size;
  1290.     }
  1291.     return 0;
  1292. }
  1293.